var express = require('express');
var router = express.Router();
var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '123456',
  database : 'node'
});
 
connection.connect();
var  sql = 'SELECT * FROM didi';
var delSql = 'DELETE FROM didi where id=?';
var  chsql='UPDATE didi SET name = ? WHERE Id = ?'
var addsql="INSERT INTO didi VALUES (?,?)"
var selsql="select * from didi where id=?"

// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
  console.log('Time: ', Date.now());
  next();
});
// define the home page route
router.get('/', function(req, res) {
  res.send('欢迎来到本就美得主页');
});
// define the about route
router.get('/about', function(req, res) {
  res.send('其实这里啥也没得！');
});
router.get('/select', function(req, res) {
  connection.query(sql,function (err, result) {
  if(err){
    console.log('[SELECT ERROR] - ',err.message);
    return;
    }
  res.send(result);
  })
});
router.get('/del',function(req,res){
  connection.query(delSql,req.query.id,function(err,del){
    if(err){
        console.log('[DELETE ERROR] - ',err.message);
        return;
      }
      res.send("id为"+req.query.id+"已经被删除");
  })
})
router.get('/ch',function(req,res){
  var id=req.query.id;
  var name=req.query.name;
  connection.query(chsql,[name,id],function(err,updata){
    if(err){
        console.log('[UPDATA ERROR] - ',err.message);
        return;
      }
      res.send("已修改");
})})
router.get('/add',function(req,res){
  var id=req.query.id
  var name=req.query.name
  connection.query(addsql,[req.query.id,req.query.name],function(err,add){
    if(err){
        console.log('[INSERT ERROR] - ',err.message);
        return;
      }
      res.send("以增加");
    })
})

router.get('/sel',function(req,res){
  connection.query(selsql,req.query.id,function(err,sel){
    if(err){
      console.log('[SELECT ERROR]',err.message)
    }
    res.send(sel)
  })

})


module.exports = router;